package com.smartsystem.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartsystem.modules.system.entity.SysPermission;
import com.smartsystem.modules.system.mapper.SysPermissionMapper;
import com.smartsystem.modules.system.service.SysPermissionService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 权限表Service实现类
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {
    
    @Resource
    private SysPermissionMapper sysPermissionMapper;
    
    @Override
    public List<SysPermission> findByUserId(Long userId) {
        return sysPermissionMapper.findByUserId(userId);
    }
    
    @Override
    public List<SysPermission> getUserMenuTree(Long userId) {
        // 查询用户拥有的所有权限
        List<SysPermission> permissions = findByUserId(userId);
        
        // 过滤出菜单类型的权限
        List<SysPermission> menus = permissions.stream()
                .filter(p -> p.getType() == 1) // 1表示菜单
                .sorted(Comparator.comparing(SysPermission::getSort))
                .collect(Collectors.toList());
        
        // 构建菜单树
        return buildMenuTree(menus, 0L);
    }
    
    /**
     * 构建菜单树
     * @param menus 菜单列表
     * @param parentId 父菜单ID
     * @return 菜单树
     */
    private List<SysPermission> buildMenuTree(List<SysPermission> menus, Long parentId) {
        List<SysPermission> tree = new ArrayList<>();
        
        // 查找当前父节点下的所有子节点
        for (SysPermission menu : menus) {
            if (Objects.equals(menu.getParentId(), parentId)) {
                // 递归查找子节点的子节点
                List<SysPermission> children = buildMenuTree(menus, menu.getId());
                menu.setChildren(children);
                tree.add(menu);
            }
        }
        
        return tree;
    }
}